import { getLocalStorage, setLocalStorage } from "@/utils/localstorage.ts";
import { LocalstorageEnum } from "@/types/localstorage.ts";
import Fingerprint2 from "fingerprintjs2"; // 引入fingerprintjs2
import DeviceDetector from "device-detector-js";
import axios from "axios";
// import { showToast } from "vant";

export const createFingerprint = async (useStorage = true) => {
  if (useStorage && getLocalStorage(LocalstorageEnum.BROWSER_ID)) {
    // showToast({
    //   message: "storage:" + JSON.stringify(getLocalStorage(LocalstorageEnum.BROWSER_ID)),
    //   duration: 10000,
    // });
    return getLocalStorage(LocalstorageEnum.BROWSER_ID);
  }

  const deviceDetector = new DeviceDetector();
  const { device, os } = deviceDetector.parse(navigator.userAgent);
  const urlJson = await axios.request({
    url: "https://api.ipify.org?format=json",
    method: "GET",
  });
  const deviceList = [
    urlJson.data.ip,
    window.devicePixelRatio,
    screen.colorDepth,
    screen.height,
    screen.width,
    // navigator.userAgent,
    JSON.stringify(device),
    JSON.stringify(os),
  ];

  console.log(deviceList, "deviceList");
  const murmur = Fingerprint2.x64hash128(deviceList.join("-")); // 生成浏览器指纹
  // showToast({
  //   message: murmur + "-----" + JSON.stringify(deviceList),
  //   duration: 10000,
  // });
  useStorage && setLocalStorage(LocalstorageEnum.BROWSER_ID, murmur);

  return murmur;
};
